<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace addons\equip\model;
use think\Db;

/**
 * Description of Equip
 * 我的装备
 * @author zmh
 */
class UnitedCreateOrder extends \web\common\model\BaseModel {


    protected function _initialize() {
        $this->tableName = 'united_create_order';
    }


    /**
     * 关联分类表列表
     * @param int $pageIndex
     * @param int $pageSize
     * @param string $filter
     * @param string $order
     * @return mixed
     */
    public function getList($pageIndex = -1, $pageSize = -1, $filter = '', $order = 'id desc') {
        $sql = 'select o.*,m.username,m.phone from ' . $this->getTableName() ." o left join tp_member_account m on m.id=o.user_id" ;
        $sql = 'select * from ('.$sql.') s';
        if (!empty($filter))
            $sql .= ' where ' . $filter;
        return $this->getDataListBySQL($sql, $pageIndex, $pageSize, $order);
    }
    

    public function getTotal( $filter = '') {
        $sql = 'select o.*,m.username,m.phone from ' . $this->getTableName() ." o left join tp_member_account m on m.id=o.user_id" ;
        $sql = 'select * from ('.$sql.') s';
        if($filter != ''){
            $sql = 'select count(*) c from ('.$sql.') as y where '.$filter;
        }else{
            $sql = 'select count(*) c from ('.$sql.')';
        }
        $result = $this->query($sql);
        if (count($result) > 0)
            return intval($result[0]['c']);
        else
            return 0;
    }


    public function createEquip($data,$is_send=0){
        $info  = [
            'e_id' => $data['id'],
            'user_id' => $data['user_id'],
            'o_sn' => '0x'.md5($data['id']. microtime()),
            'o_amount' => $data['exchange_amount'],
            'equip_name' => $data['equip_name'],
            'equip_img' => $data['equip_img'],
            'validity' => $data['validity'],
            'equip_img' => $data['equip_img'],
            'total_reward' => $data['total_reward']/2,
            'total_release' => 0,
            'today_release' => 0,
            'days_release' => $data['days_release'],
            'is_send' => $is_send,
            'start_time' => date('Y-m-d H:i:s',strtotime('+'.$data['validity'].' month')),
            // 'end_time' => date('Y-m-d H:i:s',strtotime('+'.$data['validity'].' days')),
            'create_time' => NOW_DATETIME,
            'update_time' => 0,
            // 'update_time' => NOW_DATETIME,
        ];
        return $this->add($info);
    }
    

    /**
     * 设置过期
     */
    public function setPassEquip($user_id){
        $randValue = rand(10000, 99999);    //lock
        $redis = \think\Cache::connect(\think\Config::get('global_cache'))->getHandler();
        $lockKey = 'setPassEquip'.$user_id;
        $lock = $redis->set($lockKey, $randValue, ['NX', 'EX'=>1]);    
        $script = '
            if redis.call("get",KEYS[1]) == ARGV[1] then
                return redis.call("del",KEYS[1])
            else
                return 0
            end
        ';
        if($lock) {
            $map['status'] = 0;
            $map['user_id'] = $user_id;
            $list = $this->where($map)->where(function($query){
                $query->whereOr(['end_time'=>['<=',NOW_DATETIME]])->whereOr('total_release','exp',Db::raw('>=`total_reward`'));
            })->limit(0,100)->select();
            if(!$list) {
                $redis->eval($script, [$lockKey, $randValue], 1);
                return false;
            }
            $teamM = new \addons\member\model\PhysicalContribution;
            foreach ($list as $key => $v) {
                $this->startTrans();
                $this->where('id',$v['id'])->update(['update_time'=>date('Y-m-d H:i:s'),'status'=>1]);
                //减少活跃值
                $active_value = bcdiv($v['o_amount'], 100,2);
                $res = $teamM->teamStrengthCal($user_id,$active_value,0);
                if(!$res){
                    $this->rollback();
                    return $this->failJSON('增加活跃值失败');
                }
                $this->commit();
            }
            $redis->eval($script, [$lockKey, $randValue], 1);
        }
    }
}
